package com.gyms.adapter;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.classic.okhttp.Cons;
import com.classic.okhttp.beans.HVProductInfoBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.IUserService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.classic.okhttp.zmoumall.utils.ToastUtil;
import com.gyms.R;
import com.gyms.activity.CodeLoginActivity;
import com.gyms.base.BaseActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.DataCenter;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import constant.PicSplit;
import glide.ImageLoaderUtils;
import myInterface.OnItemClickLitener;
import utils.DecimalUtils;
import utils.ScreenUtils;
import utils.StringUtils;
import weight.CommonEmptyView;

/**
 * 我的课程的适配器 yjl
 */
public class MyCourseAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<HVProductInfoBean> mHVProductInfoBeans;

    private Context mContext;
    private LayoutInflater layoutInflater;

    private View view;
    private int mScreentWidth;
    private boolean isClose = true;
    private OnItemClickLitener mOnItemClickLitener;//Item的点击监听
    private Dialog loadingView;
    private int clickposition;//点击位置
    private CommonEmptyView searchEmpty;
    private View contentView;
    private int mHeadRes;//头部资源

    public void setHeadRes(int mHeadRes){
        this.mHeadRes=mHeadRes;
    }
    private int getHeadCount(){
        return mHeadRes==0?0:1;
    }
    public MyCourseAdapter(Context context, List<HVProductInfoBean> list, int screentWidth, Dialog loadingViews, CommonEmptyView searchEmpty,View contentView) {
        this.mContext = context;
        loadingView = loadingViews;
        this.mScreentWidth = screentWidth;
        this.searchEmpty = searchEmpty;
        this.contentView=contentView;
        mHVProductInfoBeans = list;
        this.layoutInflater = LayoutInflater.from(context);
    }

    public void setData(List<HVProductInfoBean> objects) {
        this.mHVProductInfoBeans.addAll(objects);
        notifyDataSetChanged();
    }

    public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) {
        this.mOnItemClickLitener = mOnItemClickLitener;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        RecyclerView.ViewHolder mViewHolder=null;
        switch (viewType){
            case Constants.S_TYPE_HEAD://head
                View mHeadView=LayoutInflater.from(mContext).inflate(mHeadRes,parent,false);
                mViewHolder=new HeadViewHolder(mHeadView);
                break;

            case Constants.S_TYPE_NOM://正常的vIew
                View view = layoutInflater.inflate(R.layout.item_my_course, parent, false);
                 mViewHolder = new CourseViewHolder(view);
                // 设置内容view的大小为屏幕宽度,这样按钮就正好被挤出屏幕外
                ViewGroup.LayoutParams lp = ((CourseViewHolder)mViewHolder).content.getLayoutParams();
                lp.width = mScreentWidth;
                break;
        }

        return mViewHolder;
    }

    @Override
    public int getItemCount() {
        int mDataSize=null==mHVProductInfoBeans?0:mHVProductInfoBeans.size()+getHeadCount();
        return mDataSize;
    }

    @Override
    public int getItemViewType(int position) {
        if (position<getHeadCount()) return Constants.S_TYPE_HEAD;

        return Constants.S_TYPE_NOM;
    }

    public HVProductInfoBean getItem(int position) {
        return mHVProductInfoBeans.get(position);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder mViewHolder, int position) {


        int mViewType=getItemViewType(position);
        if(StringUtils.isNull(mHVProductInfoBeans)){
            return;
        }
        switch (mViewType){
            case Constants.S_TYPE_HEAD:

                break;


            case Constants.S_TYPE_NOM:
                CourseViewHolder mCourViewHolder= (CourseViewHolder) mViewHolder;
                HVProductInfoBean mProductBean = getItem(position-getHeadCount());
                if (!StringUtils.isNull(mProductBean)) {
                    initializeViews(mProductBean, mCourViewHolder);
                }
                mCourViewHolder.itemView.setTag(R.id.rb_home, position);
                mCourViewHolder.itemView.setTag(mViewHolder);
                // 设置监听事件
                mCourViewHolder.itemView.setOnTouchListener(touchListener);
                // 这里防止删除一条item后,ListView处于操作状态,直接还原
                if (mCourViewHolder.hSView.getScrollX() != 0) {
                    mCourViewHolder.hSView.scrollTo(0, 0);
                }
                mCourViewHolder.canncleBtn.setTag(position);
                mCourViewHolder.canncleBtn.setTag(R.id.textView, mViewHolder);
                mCourViewHolder.canncleBtn.setOnClickListener(onClickListener);
                break;
        }


    }

    private void initializeViews(HVProductInfoBean object, CourseViewHolder mViewHolder) {
        if (!StringUtils.isNull(object)) {
            boolean isProductOnline=object.getOnShelf();//产品是否在架上
            if(!StringUtils.isNull(object.getDiscount())){//优惠类不为null
                String discountUrl=object.getDiscount().get(0).getDiscountIcon();
                String mDiscountContent=object.getDiscount().get(0).getDiscountContent();//优惠文本
                if(!StringUtils.isNull(discountUrl)){//优惠的图片为null隐藏
                    mViewHolder.mTvDiscount.setVisibility(View.VISIBLE);
                    mViewHolder.tvProductHui.setVisibility(View.VISIBLE);
                    ImageLoaderUtils.displayBigPhoto(mContext, mViewHolder.mTvDiscount, discountUrl);

                }else{
                    mViewHolder.mTvDiscount.setVisibility(View.GONE);//icon
                    mViewHolder.tvProductHui.setVisibility(View.GONE);//优惠文本

                }
                mViewHolder.tvProductHui.setText(StringUtils.CS(mDiscountContent));
            }else{
                mViewHolder.mTvDiscount.setVisibility(View.GONE);
                mViewHolder.tvProductHui.setVisibility(View.GONE);
            }

            if(!object.refundable&&StringUtils.isNull(object.getDiscount())){//不可退款并且 优惠类为null 就隐藏
                mViewHolder.mLlDiscound.setVisibility(View.GONE);
            }else {
                mViewHolder.mLlDiscound.setVisibility(View.VISIBLE);
            }

            //是否可退款
            mViewHolder.mIvRefund.setVisibility(object.refundable?View.VISIBLE:View.GONE);
            mViewHolder.mTvRefundText.setVisibility(object.refundable?View.VISIBLE:View.GONE);
            if(object.refundable){
                ImageLoaderUtils.display(mContext,mViewHolder.mIvRefund,  PicSplit.urlAdd(Cons.S_PRODUCT_REFUND_ICON,PicSplit.TYPE_TAB));
            }


            mViewHolder.tvProductTitle.setText(StringUtils.CS(object.getProductName()));
            mViewHolder.tvAddressDetil.setText(StringUtils.CS(object.getShortAddress()));
            if (!StringUtils.isNull(object.getMinPrice()) && !StringUtils.isNull(object.getMaxPrice())) {
                if (object.getMinPrice().compareTo(object.getMaxPrice()) == 0) {
//                    mViewHolder.tvPrise.setText("￥" + DecimalUtils.doubleToIntOrD(object.getMinPrice()));
                    mViewHolder.tvPrise.setText( DecimalUtils.setPriceStyle(mContext,object.getMinPrice(),R.dimen.price_text_size_14,R.dimen.price_text_size_12,true));
                } else {
//                    mViewHolder.tvPrise.setText("￥" + DecimalUtils.doubleToIntOrD(object.getMinPrice()) + "-" + DecimalUtils.doubleToIntOrD(object.getMaxPrice()));
                    mViewHolder.tvPrise.setText(DecimalUtils.setPriceStyle(mContext,object.getMinPrice(),R.dimen.price_text_size_14,R.dimen.price_text_size_12,true).append(" - ").append( DecimalUtils.setPriceStyle(mContext,object.getMaxPrice(),R.dimen.price_text_size_14,R.dimen.price_text_size_12,false)));
                }
            }
            if (!StringUtils.isNull(object.getDistance())) {
                double dis = object.getDistance() / 1000;
                showDis(mViewHolder, dis);
            }
            mViewHolder.ivRecommend.setImageResource(R.mipmap.icon_save_subscript);
            mViewHolder.ivRecommend.setVisibility(View.VISIBLE);
//            if (object.getIsRecommend()) {
//                mViewHolder.ivRecommend.setVisibility(View.VISIBLE);
//            } else {
//                mViewHolder.ivRecommend.setVisibility(View.GONE);
//            }
            ImageLoaderUtils.display(mContext, mViewHolder.ivProductCover, object.getProductUrl());
            //如果已下架就 显示出已下架
            if(isProductOnline){
                mViewHolder.mTvGymLostView.setVisibility(View.GONE);//已上架就隐藏
            }else{
                mViewHolder.mTvGymLostView.setVisibility(View.VISIBLE);//已下架就显示
                ViewGroup.LayoutParams lpGymLostView = mViewHolder.mTvGymLostView.getLayoutParams();
                lpGymLostView.height= ScreenUtils.getViewHight(mViewHolder.content);//计算高度
            }
        }

    }
    /**
     * 小于1公里的，距离显示“<1km”；大于等于1公里，小于等于50公里的，距离显示“xx.xkm”；大于50公里的，距离显示“>50km”；
     *
     * @param dis 公里
     */
    private void showDis(CourseViewHolder mViewHolder, double dis) {
        String disText;
        if (dis < 1) {
            mViewHolder.tvDistance.setText("<1km");
        } else if (dis >= 1 && dis <= 50) {
            disText=DecimalUtils.getDistaceText(dis);
            mViewHolder.tvDistance.setText(disText + "km");
        } else {
            mViewHolder.tvDistance.setText(">50km");
        }
    }

    class CourseViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_product_cover)
        ImageView ivProductCover;
        @BindView(R.id.tv_product_title)
        TextView tvProductTitle;
        @BindView(R.id.tv_address_detil)
        TextView tvAddressDetil;
        @BindView(R.id.tv_distance)
        TextView tvDistance;
        @BindView(R.id.tv_product_hui)
        TextView tvProductHui;
        @BindView(R.id.tv_prise)
        TextView tvPrise;
        @BindView(R.id.iv_recommend)
        ImageView ivRecommend;
        @BindView(R.id.tv_discount)
        ImageView mTvDiscount;//优惠
        @BindView(R.id.hsv)
        HorizontalScrollView hSView;
        @BindView(R.id.ll_content)
        View content;
        @BindView(R.id.canncle_button)
        Button canncleBtn;
        @BindView(R.id.ll_action)
        View action;
        @BindView(R.id.tv_lost_view)
        TextView mTvGymLostView;//标识已下架的场馆
        @BindView(R.id.ll_discound)
        LinearLayout mLlDiscound;//优惠
        @BindView(R.id.iv_refund)
        ImageView mIvRefund;//可退款图标
        @BindView(R.id.tv_refund_text)
        TextView mTvRefundText;

        CourseViewHolder(View view) {
            super(view);
            AutoUtils.autoSize(view);
            ButterKnife.bind(this, view);
        }
    }

    private class HeadViewHolder extends RecyclerView.ViewHolder{

        public HeadViewHolder(View itemView) {
            super(itemView);
        }
    }


    View.OnTouchListener touchListener = new View.OnTouchListener() {

        private int y;
        private int x;
        //计算点击事件
        private float y2;
        private float x2;
        private float x1;
        private float y1;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (view != null) {
                        CourseViewHolder viewHolder1 = (CourseViewHolder) view.getTag();
                        viewHolder1.hSView.smoothScrollTo(0, 0);
                    }
                    x = (int) event.getX();
                    y = (int) event.getY();

                    x1 = event.getRawX();//得到相对应屏幕左上角的坐标
                    y1 = event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int x3 = (int) event.getX();
                    int y3 = (int) event.getY();
                    int dY = Math.abs(y - y3);
                    int dx = Math.abs(x - x3);
                    if (dx > dY && dx > 20) {
//                    		((ViewGroup) v).requestDisallowInterceptTouchEvent(true);
                    }

                    break;
                case MotionEvent.ACTION_UP:
                    // 获得ViewHolder
                    CourseViewHolder viewHolder = (CourseViewHolder) v.getTag();
                    int position = (int) v.getTag(R.id.rb_home);
                    view = v;
                    // 获得HorizontalScrollView滑动的水平方向值.
                    int scrollX = viewHolder.hSView.getScrollX();
                    // 获得操作区域的长度
                    int actionW = viewHolder.action.getWidth();

                    // 注意使用smoothScrollTo,这样效果看起来比较圆滑,不生硬
                    // 如果水平方向的移动值<操作区域的长度的一半,就复原
                    if (isClose) {
                        if (scrollX < (actionW / 5)) {
                            isClose = true;
                            viewHolder.hSView.smoothScrollTo(0, 0);
                        } else// 否则的话显示操作区域
                        {
                            isClose = false;
                            viewHolder.hSView.smoothScrollTo(actionW, 0);
                        }

                    } else {

                        if (scrollX < (actionW * 4.0 / 5.0)) {
                            isClose = true;
                            viewHolder.hSView.smoothScrollTo(0, 0);
                        } else// 否则的话显示操作区域
                        {
                            isClose = false;
                            viewHolder.hSView.smoothScrollTo(actionW, 0);
                        }
                    }

                    x2 = event.getRawX();
                    y2 = event.getRawY();
//                    Log.i("i", x1 + ",,," + y1 +",,,"+x2+",,,"+y2);
                    double distance = Math.sqrt(Math.abs(x1 - x2) * Math.abs(x1 - x2) + Math.abs(y1 - y2) * Math.abs(y1 - y2));//两点之间的距离
//                    Log.i("i", "x1 - x2>>>>>>"+ distance);
                    if (distance < 15) { // 距离较小，当作click事件来处理
                        if (mOnItemClickLitener != null) {
                            viewHolder.hSView.smoothScrollTo(0, 0);
                            mOnItemClickLitener.onItemClick(v, position-getHeadCount());
                        }
                        return false;
                    } else {
                        return true;
                    }
            }
            return false;
        }
    };

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CourseViewHolder viewHolder1 = (CourseViewHolder) v.getTag(R.id.textView);
            clickposition = (int) v.getTag();
            viewHolder1.hSView.smoothScrollTo(0, 0);
            //请求取消收藏
            sartActivityIsLogin(getItem(clickposition-getHeadCount()));
        }
    };

    /**
     * 是否登录判断跳转 ,取消收藏
     */
    public void sartActivityIsLogin(HVProductInfoBean mVVenueInfoBean) {
        if (!DataCenter.getInstance().checkIsLogin()) {
            ToastUtil.showToast(mContext, "请登录后重试");
            ((BaseActivity) mContext).startActivity(CodeLoginActivity.class, false);
        } else {
            if (!StringUtils.isNull(mVVenueInfoBean)) {
                if (loadingView != null)
                    loadingView.show();
                IUserService.cancelMyCollection((Activity) mContext, Enum.EnumCollect.Product, mVVenueInfoBean.getProductId(), false, new ObjectCallback<Object>() {
                    @Override
                    public void onSuccess(Object response, String message) {
                        mHVProductInfoBeans.remove(clickposition-getHeadCount());
                        if (mHVProductInfoBeans.size() == 0) {
                            showEmptyView(searchEmpty, 1);
                        }
                        notifyDataSetChanged();
                        ToastUtil.showToast(mContext, message);
                        if (loadingView != null) {
                            loadingView.dismiss();
                        }
                    }

                    @Override
                    public void onErrorT(int code, Object response, String errorMessage) {
                        ToastUtil.showToast(mContext, errorMessage);
                        if (loadingView != null) {
                            loadingView.dismiss();
                        }
                    }

                    @Override
                    public void onHttpErrorCall(int statusCode) {
                        if (loadingView != null) {
                            loadingView.dismiss();
                        }
                    }
                });
            }
        }
    }

    /**
     * 显示空界面或错误界面
     * @param mSearchEmpty
     * @param code  非-100为无内容界面，否则为无网络界面
     */
    protected void showEmptyView(CommonEmptyView mSearchEmpty, int code) {
        if(!StringUtils.isNull(mSearchEmpty)) {
            if (code == Constants.NO_NET) {//无网络的状态
                mSearchEmpty.setImgContent(Constants.TYPE_FAIL);
                mSearchEmpty.setVisibility(View.VISIBLE);
                contentView.setVisibility(View.GONE);
            } else {
                mSearchEmpty.setVisibility(View.VISIBLE);//空页面出现
                contentView.setVisibility(View.GONE);
                mSearchEmpty.setFailText(Constants.SEARCH_FAIL_TEXT);
                mSearchEmpty.setImgContent(Constants.TYPE_NOME);
            }
        }
    }

}
